package polimi.sc.expoquest.screen.gossip;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Random;

import polimi.sc.expoquest.QuestApplication;
import polimi.sc.expoquest.R;
import polimi.sc.expoquest.screen.DashboardActivity;
import polimi.sc.expoquest.storage.datasources.GossipCommentDataSource;
import polimi.sc.expoquest.storage.datasources.GossipDataSource;
import polimi.sc.expoquest.storage.datasources.UserDataSource;
import polimi.sc.expoquest.storage.model.Gossip;
import polimi.sc.expoquest.storage.model.GossipComment;
import polimi.sc.expoquest.storage.model.User;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class GossipMainActivity extends Activity {

	/**
	 * The gossip related datasource
	 */
	private GossipDataSource GossipDS;
	private GossipCommentDataSource GossipCommentDS;
	private Gossip CurrentGossip;
	private UserDataSource UDS;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_gossip_main);
				
		//button My Gossips
		 findViewById(R.id.mygossips).setOnClickListener(
					new View.OnClickListener() {
						@Override
						public void onClick(View view) {
							
							goMyGossips();
						}
					});
		//button Publish gossip 
		 findViewById(R.id.newgossip).setOnClickListener(
					new View.OnClickListener() {
						@Override
						public void onClick(View view) {
							
							goNewGossip();
						}
					});
		 
		//button Publish comment
		 findViewById(R.id.publishcomment).setOnClickListener(
					new View.OnClickListener() {
						@Override
						public void onClick(View view) {
							
							publishComment();
						}
					});
		 
		 //next button 
		 findViewById(R.id.next).setOnClickListener(
					new View.OnClickListener() {
						@Override
						public void onClick(View view) {
							
							goNext();
						}
					});
		 //get extra
		 int withextra=getIntent().getIntExtra("DELIVERDGOSSIP", -10);
		 
		 //get the gossip
		 if(withextra==-10)
		     goNext();
		 else //if it is from mygossiplist
		 {
			 if(GossipDS== null)
					GossipDS = new GossipDataSource(this);	    
			 GossipDS.open();		
				 CurrentGossip= GossipDS.getGossip(withextra);
			 GossipDS.close();	
			 showgossip();
		 }
		 
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_gossip_main, menu);
		return true;
	}
	public void goMyGossips()
	{
		 Intent myGossipsIntent=new Intent(this, MyGossipsActivity.class);
	     startActivityForResult(myGossipsIntent, 0);
	}
	public void goNewGossip()
	{
		 Intent newGossipIntent=new Intent(this, NewGossipActivity.class);
	     startActivityForResult(newGossipIntent, 0);
	}
	
	public void publishComment()
	{
		//get user input
		String user_input="";
		EditText commentcontent= (EditText) findViewById(R.id.gossipcomment);
		user_input= commentcontent.getText().toString();
		if(!user_input.isEmpty())
		{
		//get current user
		QuestApplication questApp = (QuestApplication)getApplicationContext();
		int userID= questApp.getUserID();
		//insert comment into database
		if(GossipCommentDS== null)
			GossipCommentDS = new GossipCommentDataSource(this);
		GossipCommentDS.open();
		//insert
		GossipCommentDS.insert (user_input, CurrentGossip.getId(),userID);
		GossipCommentDS.close();
		
		//refresh
		showcommentlist();
		//clear the userinput
		commentcontent.setText("");
		}
	}
	
	public void goNext()
	{
		//1. Creating the datasource if it isnt created already
		if(GossipDS== null)
			GossipDS = new GossipDataSource(this);
	    
		GossipDS.open();		
		Collection<Gossip> GossipContent= GossipDS.getAllGossips();
		GossipDS.close();
		
		//get a random instance
		Random generator = new Random();
		int totalgossip=GossipContent.size();
		int random=0;
		try {
			random = generator.nextInt(totalgossip);
		}
		catch(IllegalArgumentException e){}
		
		Object [] o =GossipContent.toArray();
		CurrentGossip=(Gossip)o[random];	
		
		showgossip();
		
	}
	
	public void showcommentlist()
	{
		if(GossipCommentDS== null)
			GossipCommentDS = new GossipCommentDataSource(this);
		GossipCommentDS.open();
		Collection<GossipComment> GossipCommentCollection= GossipCommentDS.getAllGossipsCommentsForGossip(CurrentGossip.getId());
		GossipCommentDS.close();
		//
		TextView tvGossipComment=(TextView)findViewById(R.id.commentofgossip);
		String gossipComment = "";	
				
		if(UDS== null)
		UDS = new UserDataSource(this);
	    UDS.open();
		for(GossipComment oneGossipComment:GossipCommentCollection)
		{
			gossipComment=gossipComment+UDS.getUser(oneGossipComment.getUser().getId()).getUsername()+" said: "+oneGossipComment.getComment() +"\n"+"\n";
		}	
		UDS.close();
		tvGossipComment.setText(gossipComment);
		
	}
	
	
	public void homepagebtn_click(View v){
		  Intent dashbordIntent = new Intent(this, DashboardActivity.class);
		        startActivity(dashbordIntent);
		 }
	
	private Drawable loadImage(String path) throws IOException
	{
		// get input stream
		InputStream ims = getAssets().open(path);
		// load image as Drawable
		Drawable d = Drawable.createFromStream(ims, null);
		return d;
	}
	
	private Drawable loadImagefromphone(String path) throws IOException
	{
		// get input stream
		File f = new File(path);
	   // load image as Drawable
		InputStream ims = new FileInputStream(f);
		Drawable d = Drawable.createFromStream(ims, null);
		return d;
	}
	private void showpic()
	{
		//show the pic of the gossip
		
		ImageView image=(ImageView)findViewById(R.id.gossipimage);
		try {
			String PicURI=CurrentGossip.getPicURI();
		   if(PicURI==null || PicURI.isEmpty() )
			{
			   image.setImageDrawable(getResources().getDrawable(R.drawable.tirivia));		   
			}
		   else
		   { 			   
			   Drawable d = loadImage(CurrentGossip.getPicURI());
			   image.setImageDrawable(d);
		   }
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Drawable d;
			try {
				d = loadImagefromphone(CurrentGossip.getPicURI());
				image.setImageDrawable(d);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
			e.printStackTrace();
		}
			
	}
	
	public void showgossip()
	{
		        //Showing gossip
				TextView tvGossip=(TextView)findViewById(R.id.gossip_text);
				String gossipContent = "";	
				gossipContent=CurrentGossip.getGossip();	
				tvGossip.setText(gossipContent);
				
				//show the pic
				showpic();
				
				//show the comment of the gossip
				showcommentlist();
				
	}
}
